package com.juzipi.demo.jdbc;

import com.juzipi.demo.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcTransactionDemo {

    public static void main(String[] args) {



        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        try {
            //获取连接
            connection = JDBCUtils.getConnection();
            //开启事务
            connection.setAutoCommit(false);

            //定义sql
            // - 500
            String sql1 = "update account set balance = balance - ? where id = ?";
            // + 500
            String sql2 = "update account set balance = balance + ? where id = ?";
            //获取执行sql对象
            preparedStatement1 = connection.prepareStatement(sql1);
            preparedStatement2 = connection.prepareStatement(sql2);
            //给 ? 赋值
            preparedStatement1.setDouble(1,500);
            preparedStatement1.setInt(2,1);

            preparedStatement2.setDouble(1,500);
            preparedStatement2.setInt(2,2);
            //执行sql
            preparedStatement1.executeUpdate();
            //制造一个异常
            int i = 10/0;
            preparedStatement2.executeUpdate();
            //提交事务
            connection.commit();


        } catch (Exception throwables) {
            //出现任何异常就直接回滚
            try {
                //判断 connection 不为null再回滚
                if (connection != null){
                    connection.rollback();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            throwables.printStackTrace();

        }finally {
            JDBCUtils.close(preparedStatement1,connection);
            JDBCUtils.close(preparedStatement2,null);
        }

    }

}
